package org.lq.sm.service.iml;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.lq.sm.dao.DictionaryDao;
import org.lq.sm.dao.impl.DictionaryDaoImpl;
import org.lq.sm.entity.Dictionary;
import org.lq.sm.entity.TypeID;
import org.lq.sm.service.DictionaryService;
import org.lq.sm.util.CastUtil;
import org.lq.sm.util.HttpUtil;

import com.google.gson.Gson;

public class DictionaryServiceImpl implements DictionaryService {

	DictionaryDao dicdao = new DictionaryDaoImpl();
	@Override
	public boolean saveDictionary(Dictionary d) {
		return dicdao.save(d) > 0;
	}

	@Override
	public boolean updateDictionaryById(Dictionary d) {
		return dicdao.update(d) > 0;
	}

	@Override
	public boolean deleteDictionaryById(int id) {
		/*
		 *  如果当前会员级别下面有会员,不可以被删除,品牌下面,单位下面,类型下面,有商品,都是不可以直接对字典数据进行删除的
		 */
		return dicdao.delete(id) > 0;
	}

	@Override
	public List<Dictionary> findDictionaryAll() {
		return dicdao.findAll();
	}

	@Override
	public Dictionary getDictionaryById(int id) {
		return dicdao.getById(id);
	}

	@Override
	public List<Dictionary> findDictionaryByTypeID(TypeID t) {
		return dicdao.findDictionaryByTypeID(t.getId());
	}

	@Override
	public boolean addDictionary(TypeID t,String name) {
		// 查询,判断当前数据库中是否存在指定的内容,如果存在,就不添加,否则添加
			Dictionary diction = dicdao.getDictionaryByTypeIDAndName(name, t.getId());
			//数据库不存在
			if(diction==null) {
				Dictionary d= new Dictionary();
				d.setName(name);
				d.setTypeid(t);
				return  saveDictionary(d);
			}
		
		return false;
	}

	@Override
	public Map<String, String> getMapByJson(String code) {
		Gson gson = new Gson();
		String json = HttpUtil.getHTTP(code);
		HashMap map = gson.fromJson(json, new HashMap().getClass());
		Map body = (Map) map.get("showapi_res_body");
		String manuName = CastUtil.castString(body.get("manuName"));
		String trademark = CastUtil.castString(body.get("trademark"));
		String manuAddress = CastUtil.castString(body.get("manuAddress"));
		String note = CastUtil.castString(body.get("note"));
		String goodsName = CastUtil.castString(body.get("goodsName"));
		String goodsType = CastUtil.castString(body.get("goodsType"));
		String price = CastUtil.castString(body.get("price"));
		
		Map<String, String> return_map = new HashMap<String, String>();
		return_map.put("manuName", manuName);
		return_map.put("trademark", trademark);
		return_map.put("manuAddress", manuAddress);
		return_map.put("note", note);
		return_map.put("goodsName", goodsName);
		return_map.put("price", price);
		
		String[] types = goodsType.split(">>");
		return_map.put("goodsType", types[types.length-1]);
		for (String type : types) {
			addDictionary(TypeID.类别, type);
		}
		addDictionary(TypeID.品牌, trademark);
		
		return return_map;
	}

	
	
}
